﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Linq;
using Xenta.Api;
using Xenta.Entities;
using Xenta.Enums;
using Xenta.Security;
using Xenta.Structs;
using Xenta.Utils;

namespace Xenta.Operations
{
    #region __General__

    /// <summary>
    /// Creates a customer.
    /// </summary>
    public class CreateCustomer : CreateAccountProfile<CustomerEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("SALES");
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .Rule((ctx, uow) => ctx.Account(uow).EntityID == AccountID);
            }
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public CustomerFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow, out CustomerEntity result)
        {
            base.Work(uow, out result);
            try
            {
                uow.Execute(new EnqueueCustomerNotification
                {
                    CustomerID = result.EntityID,
                    RecipientID = result.Account.EntityID
                });
            }
            catch(Exception ex)
            {
                uow.Execute(new CreateLogRecordFromException
                {
                    Ex = ex
                });
            }
        }

        protected override void Construct(IUnitOfWork uow, CustomerEntity entity)
        {
            base.Construct(uow, entity);

            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Updates the customer.
    /// </summary>
    public class UpdateCustomer : UpdateAccountProfile<CustomerEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("SALES");
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .Rule((ctx, uow) =>
                    {
                        var customer = ctx.Customer(uow);
                        return customer != null && customer.EntityID == EntityID;
                    });
            }
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public CustomerFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Revise(IUnitOfWork uow, CustomerEntity entity)
        {
            base.Revise(uow, entity);

            entity.Flags = Flags;
        }

        #endregion
    }

    /// <summary>
    /// Deletes the customer.
    /// </summary>
    public class DeleteCustomer : DeleteAccountProfile<CustomerEntity>,
        ISecuredOperation, IApiOperation
    {
        #region Properties

        /// <summary>
        /// Gets the collection of security policies.
        /// </summary>
        public IEnumerable<SecurityPolicy> SecurityPolicies
        {
            get
            {
                yield return new SecurityPolicy()
                    .IsAuthenticated()
                    .HasPermission("SALES");
            }
        }

        #endregion
    }

    /// <summary>
    /// Gets the customer by identifier.
    /// </summary>
    public class GetCustomer : GetAccountProfile<CustomerEntity>,
        IApiOperation
    {
    }

    /// <summary>
    /// Gets the customer by identifier.
    /// </summary>
    public class GetCustomerByAccount : GetAccountProfileByAccount<CustomerEntity>,
        IApiOperation
    {
        #region Options

        protected override bool Cacheable
        {
            get
            {
                return true;
            }
        }

        #endregion
    }

    #endregion

    #region __Search__

    /// <summary>
    /// Search over customer collection.
    /// </summary>
    public class SearchCustomers : SearchOperation<CustomerEntity>,
        IApiOperation
    {
        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public SearchCustomers()
        {
            Term = SearchTerm.Empty;
            SortDir = SortDirection.Ascending;
            SortBy = new []
            {
                CustomerSortBy.ID
            };
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the search term.
        /// </summary>
        public SearchTerm Term
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the country identifier.
        /// </summary>
        public int? CountryID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the region identifier.
        /// </summary>
        public int? RegionID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flag mask.
        /// </summary>
        public CustomerFlags FlagMask
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sort direction.
        /// </summary>
        public SortDirection SortDir
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the sort by.
        /// </summary>
        public CustomerSortBy[] SortBy
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override IQueryable<CustomerEntity> Build(IUnitOfWork uow, IQueryable<CustomerEntity> query)
        {
            query = base.Build(uow, query);
            query = query.Fetch(x => x.Account);
            query = query.FilterByFlags(x => (int)x.Flags, (int)FlagMask);
            switch(Term.Mode)
            {
                case SearchTerm.SearchMode.StartsWith:
                    query = query.Where(x =>
                        x.Account.Email.StartsWith(Term.Keyword) ||
                        x.Account.Username.StartsWith(Term.Keyword));
                    break;
                case SearchTerm.SearchMode.EndsWith:
                    query = query.Where(x =>
                        x.Account.Email.EndsWith(Term.Keyword) ||
                        x.Account.Username.EndsWith(Term.Keyword));
                    break;
                case SearchTerm.SearchMode.Contains:
                    query = query.Where(x =>
                        x.Account.Email.Contains(Term.Keyword) ||
                        x.Account.Username.Contains(Term.Keyword));
                    break;
                case SearchTerm.SearchMode.Equals:
                    query = query.Where(x =>
                        x.Account.Email.Equals(Term.Keyword) ||
                        x.Account.Username.Equals(Term.Keyword));
                    break;
            }
            if(CountryID.HasValue)
                query = query.Where(x => x.Addresses.Any(i => i.Country.EntityID == CountryID.Value));
            if(RegionID.HasValue)
                query = query.Where(x => x.Addresses.Any(i => i.Region.EntityID == RegionID.Value));
            if(SortBy != null)
            {
                for(int i = 0; i < SortBy.Length; i++)
                {
                    switch(SortBy[i])
                    {
                        case CustomerSortBy.CreatedOn:
                            query = query.OrderBy(x => x.CreatedOn, SortDir, i != 0);
                            break;
                        default:
                            query = query.OrderBy(x => x.EntityID, SortDir, i != 0);
                            break;
                    }
                }
            }
            return query;
        }

        #endregion
    }

    /// <summary>
    /// Gets the collection of file owners as a dictionary, where 
    /// key - customer identifier and value - account email.
    /// </summary>
    public class GetCustomerDictionary : SearchOperation<CustomerEntity, Int32, String>,
        IApiOperation
    {
        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public GetCustomerDictionary()
        {
            Term = SearchTerm.Empty;
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the search term.
        /// </summary>
        public SearchTerm Term
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flag mask.
        /// </summary>
        public CustomerFlags FlagMask
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override IQueryable<CustomerEntity> Build(IUnitOfWork uow, IQueryable<CustomerEntity> query)
        {
            query = base.Build(uow, query);
            query = query.Fetch(x => x.Account);
            query = query.FilterByFlags(x => (int)x.Flags, (int)FlagMask);
            switch(Term.Mode)
            {
                case SearchTerm.SearchMode.StartsWith:
                    query = query.Where(x =>
                        x.Account.Email.StartsWith(Term.Keyword) ||
                        x.Account.Username.StartsWith(Term.Keyword));
                    break;
                case SearchTerm.SearchMode.EndsWith:
                    query = query.Where(x =>
                        x.Account.Email.EndsWith(Term.Keyword) ||
                        x.Account.Username.EndsWith(Term.Keyword));
                    break;
                case SearchTerm.SearchMode.Contains:
                    query = query.Where(x =>
                        x.Account.Email.Contains(Term.Keyword) ||
                        x.Account.Username.Contains(Term.Keyword));
                    break;
                case SearchTerm.SearchMode.Equals:
                    query = query.Where(x =>
                        x.Account.Email.Equals(Term.Keyword) ||
                        x.Account.Username.Equals(Term.Keyword));
                    break;
            }
            query = query.OrderBy(x => x.Account.Email);
            return query;
        }

        protected override IQueryable<KeyValuePair<Int32, String>> Map(IQueryable<CustomerEntity> query)
        {
            return query.Select(x => new KeyValuePair<Int32, String>(x.EntityID, x.Account.Email));
        }

        #endregion
    }

    #endregion

    #region __Notification__

    /// <summary>
    /// Enqueues a customer notification message.
    /// </summary>
    /// <remarks>
    /// Message template code: ICSTMR
    /// Allowed tokens: [T:Recipient.EntityID], [T:Recipient.Guid], [T:Recipient.Email], [T:Recipient.Username],
    /// [T:Customer.Account.EntityID], [T:Customer.Account.Guid], [T:Customer.Account.Email], [T:Customer.Account.Username],
    /// [T:Customer.EntityID]
    /// </remarks>
    public class EnqueueCustomerNotification : Operation<MessageEntity>
    {
        #region Properties

        /// <summary>
        /// Gets or sets the customer identifier.
        /// </summary>
        public int CustomerID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the recipient account identifier.
        /// </summary>
        public int RecipientID
        {
            get;
            set;
        }

        #endregion

        #region Utilities

        protected override void Work(IUnitOfWork uow, out MessageEntity result)
        {
            var customer = uow.Execute(new GetCustomer
            {
                ThrowsException = true,
                EntityID = CustomerID
            }).Result;
            var recipient = customer.Account.EntityID == RecipientID ? customer.Account : uow.Execute(new GetAccount
            {
                ThrowsException = true,
                EntityID = RecipientID
            }).Result;
            var usrLocale = recipient.LocalizationProfile;

            result = uow.Execute(new CreateTemplatedMessageByCode
            {
                TemplateCode = "ICSTMR",
                LanguageID = usrLocale.Language.EntityID,
                Replacements = new Dictionary<String, String>
                {
                    {"Recipient.EntityID", recipient.EntityID.ToString()},
                    {"Recipient.Email", recipient.Email},
                    {"Recipient.Username", recipient.Username},
                    {"Recipient.Guid", recipient.Guid.ToString()},
                    {"Customer.Account.EntityID", customer.Account.EntityID.ToString()},
                    {"Customer.Account.Email", customer.Account.Email},
                    {"Customer.Account.Username", customer.Account.Username},
                    {"Customer.Account.Guid", customer.Account.Guid.ToString()},
                    {"Customer.EntityID", customer.EntityID.ToString()}
                },
                To = recipient.Email,
                Flags = MessageFlags.Active
            }).Result;
        }

        #endregion
    }

    #endregion
}
